import nedb from './nedb'

export default {
  /**
   * 添加用户登录
   * @param {Object} user 用户信息
   */
  async setUser (user) {
    try {
      var result = await nedb.user_login.find({cs_id: user.cs_id})
      if (result.length > 0) { // 已经存在了更新数据
        await nedb.user_login.update({cs_id: user.cs_id}, user)
      } else { // 不存在添加数据
        await nedb.user_login.insert(user)
      }
      return Promise.resolve(user)
    } catch (e) {
      return Promise.resolve(null)
    }
  },
  /**
   * 获取客服信息 cs_id不传的话获取全部客服
   * @param {Number} csid 客服ID
   */
  async getUser (csid) {
    try {
      var result
      if (csid) {
        result = await nedb.user_login.find({cs_id: csid})
      } else {
        result = await nedb.user_login.find({})
      }
      return Promise.resolve(result)
    } catch (e) {
      return Promise.resolve([])
    }
  },
  /**
   * 通过用户名查找用户
   * @param {String} name 用户账号
   */
  async nameTouser (name) {
    try {
      var result
      if (name) {
        result = await nedb.user_login.find({'info.username': name})
      } else {
        result = await nedb.user_login.find({})
      }
      return Promise.resolve(result)
    } catch (e) {
      return Promise.resolve([])
    }
  },
  /**
   * 删除客服信息
   * @param {Number} csid 客服ID
   */
  async delUser (csid) {
    try {
      var result = await nedb.user_login.remove({cs_id: csid}, {})
      return Promise.resolve(result)
    } catch (e) {
      return Promise.resolve(null)
    }
  },
  /**
   * 更新全部客服信息
   * @param {Array} list 客服ID
   */
  async updataUser (list) {
    try {
      await nedb.user_login.remove({}, { multi: true }) // 删除全部的
      var addlist = await nedb.user_login.insert(list)
      return Promise.resolve(addlist)
    } catch (e) {
      return Promise.resolve(null)
    }
  }
}
